//
//  BPHeartMakeCenterView.m
//  BeautyPicture
//
//  Created by 沈振邦 on 15/9/18.
//  Copyright (c) 2015年 szb. All rights reserved.
//

#import "BPHeartMakeCenterView.h"
#import "BPProductModel.h"
#import "BPImageTool.h"
#import "UIColor+Extension.h"
#import "BPCustomLabel.h"

#define ImageCahes [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]

@interface BPHeartMakeCenterView (){
    CGFloat imgBackW;
    CGFloat imgBackH;
    
}

@property(nonatomic,weak)BPProductModel *modelInfo;

@end

@implementation BPHeartMakeCenterView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor whiteColor];
        self.userInteractionEnabled = YES;
        self.clipsToBounds = YES;
        [self setUpFontData];
        
        
        // 底纹的尺寸
        // 高度
        if (imgBackW == 0.00 && imgBackH == 0.00 ) {
            imgBackW = 600;
            imgBackH = 884;
        }else {
            
            imgBackW =  [[[NSUserDefaults standardUserDefaults]objectForKey:@"DWH"] floatValue];
            imgBackH = [[[NSUserDefaults standardUserDefaults]objectForKey:@"DWW"] floatValue];
        }
        

        // 目标imgView大小
        CGFloat imgTargetW = 170;
        CGFloat imgTargetH = (imgTargetW * imgBackH) / imgBackW;
        // 背景view的宽高
        CGFloat viewBackW = self.frame.size.width;
        CGFloat viewBackH = self.frame.size.height;
        // 每一行显示的个数
        NSInteger column_count = (int)((viewBackW / imgTargetW) + 1);
        // 显示多少行
        NSInteger row_count = (int)(viewBackH / imgTargetH) + 1;
        
        _numXY = column_count * row_count;
        // 循环创建
        for (int i = 0; i < column_count * row_count; i++) {
            // 初始化
            _shadingView1 = [[UIImageView alloc] init];
            _shadingView1.tag = 500 + i;
            // 求出每个横坐标
            CGFloat X = (imgTargetW) * (i % column_count);
            // 求出每个纵坐标
            CGFloat Y = (imgTargetH) * (i / column_count);
            _shadingView1.frame = CGRectMake(X, Y, imgTargetW, imgTargetH);
            //            _shadingView1.backgroundColor = [UIColor redColor];
            //            _shadingView1.image = [UIImage imageNamed:@"15.jpg"];
            _shadingView1.alpha = 0.9f;
            [self addSubview:_shadingView1];
        }
        
        //2.设置底纹层
//        _shadingView1 = [[UIImageView alloc] initWithFrame:self.bounds];
//        _shadingView1.alpha = 0.9f;
//        _shadingView1.tag = 500;
////        _shadingView1.contentMode = UIViewContentModeScaleAspectFit;
//        [self addSubview:_shadingView1];

        
//        _shadingView2 = [[UIImageView alloc] initWithFrame:CGRectMake(self.frame.size.width / 2, 0, self.frame.size.width / 2, self.frame.size.height / 1.35)];
//        _shadingView2.alpha = 0.9f;
//        _shadingView2.contentMode = UIViewContentModeScaleAspectFit;
//        [self addSubview:_shadingView2];
//        
//        
//        _shadingView3 = [[UIImageView alloc] initWithFrame:CGRectMake(0, self.frame.size.height / 1.35, self.frame.size.width / 2, self.frame.size.height / 1.35)];
//        _shadingView3.alpha = 0.9f;
//        _shadingView3.contentMode = UIViewContentModeScaleAspectFit;
//        [self addSubview:_shadingView3];
//        
//        
//        _shadingView4 = [[UIImageView alloc] initWithFrame:CGRectMake(self.frame.size.width / 2, self.frame.size.height / 1.35, self.frame.size.width / 2, self.frame.size.height / 1.35)];
//        _shadingView4.alpha = 0.9f;
//        _shadingView4.contentMode = UIViewContentModeScaleAspectFit;
//        [self addSubview:_shadingView4];
        
        
        //3.设置照片层(有可能是多张)
        _assetView = [[UIView alloc] initWithFrame:self.bounds];
        _assetView.backgroundColor = [UIColor clearColor];
        [self addSubview:_assetView];
        
        //4.设置一些固定的图片，图形层
        _cartoonView = [[UIImageView alloc] initWithFrame:self.bounds];
        _cartoonView.userInteractionEnabled = YES;
        _cartoonView.backgroundColor = [UIColor clearColor];
        [self addSubview:_cartoonView];
        
        
        
         UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(lllll:)];
        [_cartoonView addGestureRecognizer:tap];

    }
    return self;
}


- (void)lllll:(UITapGestureRecognizer *)lllll{
    
    NSLog(@"444");
    NSNotification * notice = [NSNotification notificationWithName:@"123" object:nil userInfo:nil];
    //发送消息
    [[NSNotificationCenter defaultCenter]postNotification:notice];
    
    
}


- (void)setUpFontData
{
    NSArray *textFonts = [NSArray arrayWithObjects:@"FZHTJW--GB1-0",@"FZZDXJW--GB1-0",@"FZQKBYSJW--GB1-0",@"FZXXLFW--GB1-0",@"FZJLJW--GB1-0", nil];
    NSArray *serviceFont = [NSArray arrayWithObjects:@"fangzhengheiti",@"fangzhenjianti",@"fzqkbysjianti",@"fzxxlfw",@"xjlfont", nil];
    _textFont = [NSMutableDictionary dictionary];
    _servriceFont = [NSMutableDictionary dictionary];
    for (int i = 0; i < textFonts.count; i ++) {
        [_textFont setValue:textFonts[i] forKey:serviceFont[i]];
        [_servriceFont setValue:serviceFont[i] forKey:textFonts[i]];
    }
}

- (void)setUpUserEnableView:(BPProductDetailPage *)pageInfo withScale:(CGFloat)scale addAssetarry:(NSMutableArray *)assetArry addimageScale:(CGFloat)imageScale addDiySize:(CGSize)diySize
{
    if (pageInfo.shading == nil) {
        self.shadingView1.image = nil;
//        self.shadingView2.image = nil;
//        self.shadingView3.image = nil;
//        self.shadingView4.image = nil;
    }else{
//        [BPImageTool setUpHDImageView:self.shadingView1 addNsstringUrl:pageInfo.shading];
//        [BPImageTool setUpHDImageView:self.shadingView2 addNsstringUrl:pageInfo.shading];
//        [BPImageTool setUpHDImageView:self.shadingView3 addNsstringUrl:pageInfo.shading];
//        [BPImageTool setUpHDImageView:self.shadingView4 addNsstringUrl:pageInfo.shading];
        
        
        // 根据作品scale获得
        NSString *string = [[NSUserDefaults standardUserDefaults]objectForKey:@"SCALE"];
        float SCC =100 * [string floatValue];
        NSLog(@"%f",SCC);
        
        
        for (int i = 0; i < _numXY; i ++) {
            for (UIView *ii in self.subviews) {
                if (ii.tag == (500 + i)) {
                    //[BPImageTool getNSStringURL:[NSString stringWithFormat:@"%@?imageMogr2/thumbnail/!%fp", pageInfo.shading,SCC] setImageView:(UIImageView *)ii];
                    [BPImageTool getNSStringURL:pageInfo.shading setImageView:(UIImageView *)ii];
                }
            }
        }
    }
    if (pageInfo.bg_img == nil) {
        self.cartoonView.image = nil;
    }else{
        [BPImageTool setUpHDImageView:self.cartoonView addNsstringUrl:pageInfo.bg_img];
    }
    if (![pageInfo.bg_color isEqualToString:@""]) {
        self.backgroundColor = [UIColor colorWithHexString:pageInfo.bg_color];
    }else{
        self.backgroundColor = [UIColor whiteColor];
    }
    
    if (pageInfo.moulds != nil) {
        
        [self addModelInfo:pageInfo.moulds addScale:scale addAssetarry:assetArry add:imageScale add:diySize];
    }
    
}

//配置model信息（可能是图片可能是文字）
- (void)addModelInfo:(NSArray *)modelInfo addScale:(CGFloat)scale addAssetarry:(NSMutableArray *)assetArry add:(CGFloat)imageScale add:(CGSize)diySize
{
    for (BPProductModel *model in modelInfo) {
        if (model.type == 0) {
            [self imageModelInfo:model addScale:scale addAssetarry:assetArry add:imageScale];
        }else{
            [self textModelInfo:model addScale:scale add:diySize];
        }
    }
}
//配置图片信息
- (void)imageModelInfo:(BPProductModel *)imageModel addScale:(CGFloat)scale addAssetarry:(NSMutableArray *)assetArry add:(CGFloat)imageScale
{
    BPCustomView *customView = [[BPCustomView alloc] init];
    customView.maxScale = imageScale;
    
    if (assetArry.count > 0) {
        [customView addImageModel:imageModel addScale:scale addAssetarry:assetArry[imageModel.modelIndex]];
    }
    
    [self fadeViewIn:customView];
}

- (void)fadeViewIn:(BPCustomView *)popupView
{
    popupView.alpha = 0.0f;
    
    [UIView animateWithDuration:0.5 animations:^{
        popupView.alpha = 1.0f;
    } completion:^(BOOL finished) {
    }];
    
    [self.assetView addSubview:popupView];
}

//配置文字信息
- (void)textModelInfo:(BPProductModel *)textModel addScale:(CGFloat)scale add:(CGSize)diySize
{
    BPCustomLabel *customText = [[BPCustomLabel alloc] init];
    customText.x = textModel.x * scale;
    customText.y = textModel.y * scale;
    customText.textfontSize = textModel.size * scale;
    customText.diyAreaSize = diySize;
    customText.tag = textModel.modelIndex;
    customText.textDirection = textModel.font_direct;
    customText.textColor = [UIColor colorWithHexString:textModel.color];
    UIFont *textFont = [UIFont fontWithName:_textFont[textModel.font] size:textModel.size * scale];
    customText.sbfont = _textFont[textModel.font];
    customText.font = textFont;
    if (textModel.font_direct == 0) {
        //水平
        [customText horizontalSetUpText:textModel.text];
    }else{
        //垂直
        [customText verticalSetUpText:textModel.text];
    }
    [self addSubview:customText];
}

//根据字体大小来确定textfiled的size
- (CGSize)withTestFont:(UIFont *)textFont withText:(NSString *)text
{    
    CGSize maxSize = CGSizeMake(self.width, MAXFLOAT);
    NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys: textFont, NSFontAttributeName, nil];
    CGSize textSize = [text boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:dic context:nil].size;
    return textSize;
}

- (void)savePageInfo:(BPProductDetailPage *)pageModel
{
    NSMutableArray *imgModelArry = [NSMutableArray array];
    for (BPProductModel *model in pageModel.moulds) {
        
        if (model.type == 0) {
            [imgModelArry addObject:model];
        }
    }
    
    int i = 0;
    for (id subobject in self.assetView.subviews) {
        if ([subobject isKindOfClass:[BPCustomView class]]) {
            //1.取出customview
            _senderView = (BPCustomView *)subobject;
            //2.取出对应的mould
            self.modelInfo = imgModelArry[i];
            //3.存对应的transform
            self.modelInfo.matrix = NSStringFromCGAffineTransform(_senderView.assetImage.transform);
            //4.存对应的滤镜编号
        }
//        else{
//            _senderText = (UITextField *)subobject;
//            self.modelInfo = pageModel.moulds[i];
//            self.modelInfo.text = _senderText.text;
//        }
        i = i + 1;
    }
}

//- (BOOL)checkpxIsmuch
//{
//    for (id subject in self.assetView.subviews) {
//        if ([subject isKindOfClass:[BPCustomView class]]) {
//            BPCustomView *cview = subject;
//            if (cview.nopxImage != nil) {
//                return NO;
//            }
//        }
//    }
//    return YES;
//}

- (UIImage *)setUpANewImage:(CGSize)orgImageSize
{
    for (id subject in self.assetView.subviews) {
        if ([subject isKindOfClass:[BPCustomView class]]) {
            BPCustomView *cview = subject;
            cview.nopxImage.hidden = YES;
            cview.imageVBlock.hidden = YES;
        }
    }
    UIImage* image = nil;
    if(&UIGraphicsBeginImageContextWithOptions != NULL)
    {
        UIGraphicsBeginImageContextWithOptions(self.size, NO, 2.5);
    } else {
        UIGraphicsBeginImageContext(self.size);
    }
    {
        //CGRect savedFrame = self.frame;
        
        CGRect savedFrame = self.frame;
        //scrollView.contentOffset = CGPointZero;
        //self.frame = CGRectMake(0, 0, BPScreenW, BPScreenH);
        
        [self.layer renderInContext: UIGraphicsGetCurrentContext()];
        image = UIGraphicsGetImageFromCurrentImageContext();
        
        //scrollView.contentOffset = savedContentOffset;
        self.frame = savedFrame;
        
//        [self.layer renderInContext: UIGraphicsGetCurrentContext()];
//        image = UIGraphicsGetImageFromCurrentImageContext();

        //self.frame = savedFrame;
    }
    UIGraphicsEndImageContext();
    for (id subject in self.assetView.subviews) {
        if ([subject isKindOfClass:[BPCustomView class]]) {
            BPCustomView *cview = subject;
            cview.nopxImage.hidden = NO;
            cview.imageVBlock.hidden = NO;
        }
        
    }
    if (image != nil) {
        return image;
        //[self OriginImage:image scaleToSize:CGSizeMake(self.width *3.0, self.height *3.0)];
        //[self OriginImage:image scaleToSize:CGSizeMake(2000, 2000)];
    }
    return nil;
    
}

-(UIImage*) OriginImage:(UIImage *)image scaleToSize:(CGSize)size
{
    UIGraphicsBeginImageContext(size);  //size 为CGSize类型，即你所需要的图片尺寸
    
    [image drawInRect:CGRectMake(0, 0, size.width, size.height)];
    
    UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    
    return scaledImage;   //返回的就是已经改变的图片
}

- (void)resetAssetView
{
    for (id subobject in self.assetView.subviews) {
        [subobject removeFromSuperview];
    }
    for (id subobj in self.subviews) {
        if ([subobj isKindOfClass:[BPCustomLabel class]]) {
            [subobj removeFromSuperview];
        }
    }
    self.shadingView1.image = nil;
//    self.shadingView2.image = nil;
//    self.shadingView3.image = nil;
//    self.shadingView4.image = nil;
    self.cartoonView.image = nil;
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
